/**
 * Created by Administrator on 2015/1/29.
 */
var mongoose = require('mongoose');
var logger = require('./logger');
var async = require('async');

var Config = require("./config").Config();
var mongoInfo = Config.mongoInfo;
mongoose.connect(mongoInfo.uri, mongoInfo);
var MONGO_GAME = "game";
var Schema = mongoose.Schema;
var GameSchema = new Schema({
    gameId: { type: String, unique: true },
    createUser: String,
    humanWord: String,
    length: Number,
    soulWord: String,
    status: { type: Number, default: 0 },  //状态，0为新建，1为已开始，2为已结束
    time: String
});
mongoose.model(MONGO_GAME, GameSchema);
var Game = mongoose.model(MONGO_GAME);


exports.getMongoInstance = function () {
    return mongoose;
}

exports.newGame = function (gameInfo) {
    var game = new Game({
        gameId: gameInfo.gameId,
        createUser: gameInfo.createUser,
        humanWord: gameInfo.humanWord,
        soulWord: gameInfo.soulWord,
        length: gameInfo.length,
        time: gameInfo.time
    });
    game.save(function (err) {
        if (err) logger.error("mongo error" + err);
        return
    });
}

exports.checkRoomExist = function (gameId) {
    var roomExist = null;
    var promise = Game.find({gameId: gameId}).exec();
    promise.then(function (results) {
        if (err)logger.error("mongo error" + err);
        if (results || results.length == 0) {
            roomExist = false;
        }
        else {
            roomExist = true;
        }
        logger.debug("RoomExist result", results);
        return roomExist;
    });
    logger.debug("async roomExist finish flag:"+roomExist);
}

//exports.checkRoomExist = function (gameId) {
//    var roomExist = null;
//    async.parallel([function(){
//        logger.debug("insert mongo before!")
//    },
//        function () {
//            Game.find({gameId: gameId}).exec(function (err, results) {
//                if (err)logger.error("mongo error" + err);
//
//                if (results || results.length == 0) {
//                    roomExist = false;
//                }
//                else {
//                    roomExist = true;
//                }
//                logger.debug("RoomExist result", results);
//            });
//        },function(){
//            logger.debug("insert mongo after!")
//        }
//    ], function(err, result){
//        logger.debug("async roomExist flag",roomExist);
//        return roomExist;
//    });
//    logger.debug("async roomExist finish flag:"+roomExist);
//}